<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title></title>
    <style>
      html,
      body {
        margin: 0;
        padding: 0;
      }
      body {
        height: 1000px;
      }
      #box {
        width: 100px;
        height: 100px;
        background: red;
      }
    </style>
  </head>
  <body>
    <div id="box"></div>
    <script>
      const $ = (selector) => document.querySelector(selector);

      const box = $("#box");
      const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      const scrollLeft =
        document.documentElement.scrollLeft || document.body.scrollLeft;

      document.onmousemove = (ev) => {
        const x = ev.pageX; // 如果使用 ev.clientX(可视区域) 需要 + scrollLeft
        const y = ev.pageY; // 如果使用 ev.clientY 需要 + scrollTop

        if (ev.keyCode == 37) {
          alert("左");
        } else if (ev.keyCode == 39) {
          alert("右");
        }

        box.style.transform = `translate(${x}px, ${y}px)`;
      };
    </script>
  </body>
</html>
